package name.matthewgreet.example3.common; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.ValidationAware; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; import com.opensymphony.xwork2.interceptor.PreResultListener; import com.opensymphony.xwork2.util.CompoundRoot; /** * <P>If the action implements ValidationAware, amalgametes all action errors and messages from other validation aware * actions in the Value Stack.</P> * * <H3>Interceptor parameters</H3> * <P>None</P> * * <H3>Extending the interceptor</H3> * <P>This can't be usefully extended.</P> * * <H3>Example code</H3> * <PRE> * @InterceptorRefs({ * @InterceptorRef(value="messageAmalgamation"), * @InterceptorRef(value="defaultStack") *}) * </PRE> */ public class MessageAmalgamationInterceptor extends AbstractInterceptor implements PreResultListener { private static final long serialVersionUID = -6747732006176118658L; private void amalgamateMessages(ValidationAware viewAction, ActionInvocation invocation) { ValidationAware other; CompoundRoot root; Collection<String> actionErrors, actionMessages; List<String> fieldErrors; Map<String,List<String>> allFieldErrors; actionErrors = viewAction.getActionErrors(); actionMessages = viewAction.getActionMessages(); allFieldErrors = viewAction.getFieldErrors(); root = invocation.getStack().getRoot(); for (Object o: root) { // Copy messages from anything that can hold them except the target itself if (o instanceof ValidationAware && (o != viewAction)) { other = (ValidationAware)o; actionErrors.addAll(other.getActionErrors()); actionMessages.addAll(other.getActionMessages()); for (Entry<String,List<String>> entrySet: other.getFieldErrors().entrySet()) { fieldErrors = allFieldErrors.get(entrySet.getKey()); if (fieldErrors == null) { fieldErrors = new ArrayList<String>(); } fieldErrors.addAll(entrySet.getValue()); allFieldErrors.put(entrySet.getKey(), fieldErrors); } } } viewAction.setActionErrors(actionErrors); viewAction.setActionMessages(actionMessages); viewAction.setFieldErrors(allFieldErrors); } @Override public void beforeResult(ActionInvocation invocation, java.lang.String resultCode) { Action action; action = (Action)invocation.getAction(); if (action instanceof ValidationAware) { amalgamateMessages((ValidationAware)action, invocation); } } @Override public String intercept(ActionInvocation invocation) throws Exception { invocation.addPreResultListener(this); return invocation.invoke(); } }